package com.jqing.lib.tools;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * Created by chshqiang on 15-6-18.
 * 日期时间工具类
 */
public class DatetimeTools {

    public static String formatMillis4Duration(long millis) {
        if (millis <= 0) {
            return "00:00:00";
        }
        boolean negative = millis < 0;
        millis = Math.abs(millis);

        millis /= 1000;
        int sec = (int) (millis % 60);
        millis /= 60;
        int min = (int) (millis % 60);
        millis /= 60;
        int hours = (int) millis;

        String time;
        DecimalFormat format = (DecimalFormat) NumberFormat
                .getInstance(Locale.US);
        format.applyPattern("00");
        if (millis > 0) {
            time = (negative ? "-" : "") + String.format("%02d:%02d:%02d", hours, min, sec);
        } else {
            time = (negative ? "-" : "") + String.format("%02d:%02d", min, sec);
        }
        return time;
    }

    /**
     * @return 返回前天的日期字符串
     */
    public static String getBeforeday() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(new Date(System.currentTimeMillis() - getOneDayMillis() * 2));
    }

    /**
     * @return 返回昨天的日期字符串
     */
    public static String getYesterday() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(new Date(System.currentTimeMillis() - getOneDayMillis()));
    }

    /**
     * @return 返回今天的日期字符串
     */
    public static String getTodayDate() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(new Date());
    }

    /**
     * @return 返回今天的时间字符串
     */
    public static String getTodayTime() {
        SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
        return format.format(new Date());
    }

    /**
     * @return 返回今天的时期字符串
     */
    public static String getToday() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss E");
        return format.format(new Date());
    }

    /**
     * @return 返回今天的时期字符串
     */
    public static String getTime4Millis(long timeMillis, String pattern) {
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        return format.format(new Date(timeMillis));
    }

    /**
     *
     * @return 返回一天的毫秒数
     */
    public static long getOneDayMillis() {
        return 86400000l; // 1000l * 60 * 60 * 24
    }

    public static String getTimeForDatetime(String datetime) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(datetime, pos);

        formatter = new SimpleDateFormat("HH:mm");
        return formatter.format(strtodate);
    }
}
